package com.dhcc.core.framework.security.client.hos;

import com.alibaba.fastjson.JSONObject;
import com.dhcc.core.config.properties.SsoProperties;
import com.github.scribejava.core.model.OAuth2AccessToken;
import org.pac4j.core.exception.HttpAction;
import org.pac4j.core.profile.ProfileHelper;
import org.pac4j.core.profile.converter.Converters;
import org.pac4j.oauth.config.OAuth20Configuration;
import org.pac4j.oauth.profile.definition.OAuth20ProfileDefinition;

import static org.pac4j.core.profile.AttributeLocation.PROFILE_ATTRIBUTE;

public class HosProfileDefinition extends OAuth20ProfileDefinition<HosProfile, OAuth20Configuration> {

    public static final String USER_CODE = "accountCode";

    public HosProfileDefinition() {
        primary(USER_CODE, Converters.STRING);
    }

    @Override
    public String getProfileUrl(final OAuth2AccessToken accessToken,
                                final OAuth20Configuration configuration) {
        return SsoProperties.me().getHosBackendUrl() + "/resource/getUserInfo?access_token=" + accessToken.getAccessToken();
    }

    @Override
    public HosProfile extractUserProfile(final String body) throws HttpAction {
        final HosProfile profile = new HosProfile();
//        final JsonNode json = JsonHelper.getFirstNode(body);
        final JSONObject jsonObj = JSONObject.parseObject(body);
        final JSONObject paramObj = jsonObj.getJSONObject("data");
        if (paramObj != null) {
//            profile.setId(ProfileHelper.sanitizeIdentifier(profile, JsonHelper.getElement(json, USER_CODE)));
            profile.setId(ProfileHelper.sanitizeIdentifier(profile, paramObj.getString(USER_CODE)));
            for (final String attribute : getPrimaryAttributes()) {
                convertAndAdd(profile, PROFILE_ATTRIBUTE, attribute,
//                        JsonHelper.getElement(json, attribute));
                        paramObj.getString(attribute));
            }
        } else {
            raiseProfileExtractionJsonError(body);
        }
        return profile;
    }

}
